package com.um.weixin.pay.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.github.binarywang.wxpay.bean.transfer.QueryTransferBatchesRequest;
import com.github.binarywang.wxpay.bean.transfer.QueryTransferBatchesResult;
import com.github.binarywang.wxpay.bean.transfer.TransferBatchesRequest;
import com.github.binarywang.wxpay.bean.transfer.TransferBatchesResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.um.weixin.pay.service.WxTransferService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Title 微信商家转账
 * @Description
 * @Author renjunwei
 * @Date 2023/10/10 15:55
 */
@Slf4j
@Component
public class WxTransferServiceImpl implements WxTransferService {

    @Autowired
    WxPayService wxPayService;

    /**
     * <pre>
     *
     * 发起商家转账API
     *
     * 请求方式：POST（HTTPS）
     * 请求地址：<a href="https://api.mch.weixin.qq.com/v3/transfer/batches">请求地址</a>
     *
     * 文档地址：<a href="https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter4_3_1.shtml">发起商家转账API</a>
     * </pre>
     *
     * @param openId     转账请求参数
     * @param outTradeNo 转账请求参数
     * @param amount     转账请求参数
     * @return TransferBatchesResult 转账结果
     * @throws WxPayException .
     */
    @Override
    public TransferBatchesResult transfer(String openId, String outTradeNo, Integer amount, String remark) throws WxPayException {
        //发起商家转账
        TransferBatchesRequest.TransferDetail transferDetail = new TransferBatchesRequest.TransferDetail();
        transferDetail.setOutDetailNo(outTradeNo);
        transferDetail.setTransferAmount(amount);
        transferDetail.setOpenid(openId);
        transferDetail.setTransferRemark(remark);

        TransferBatchesRequest request = new TransferBatchesRequest();
        request.setAppid(wxPayService.getConfig().getAppId());
        request.setOutBatchNo(outTradeNo);
        request.setBatchName(remark);
        request.setBatchRemark(remark);
        request.setTotalAmount(amount);
        request.setTotalNum(1);
        request.setTransferDetailList(ListUtil.toList(transferDetail));

        log.info("发起商家转账给用户-{}", cn.hutool.json.JSONUtil.toJsonStr(request));

        TransferBatchesResult transferBatchesResult = wxPayService.getTransferService().transferBatches(request);
        log.info("商家转账给用户结果-{}", cn.hutool.json.JSONUtil.toJsonStr(transferBatchesResult));
        return transferBatchesResult;
    }

    /**
     * <pre>
     *
     * 商家批次单号查询批次单API
     *
     * 请求方式：GET（HTTPS）
     * 请求地址：<a href="https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/{out_batch_no}">请求地址</a>
     *
     * 文档地址：<a href="https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter4_3_5.shtml">商家批次单号查询批次单API</a>
     * </pre>
     *
     * @param outTradeNo 查询请求参数
     * @return TransferBatchesResult 查询结果
     * @throws WxPayException .
     * @throws WxPayException .
     */
    @Override
    public QueryTransferBatchesResult.TransferDetail queryTransfer(String outTradeNo) throws WxPayException {
        QueryTransferBatchesRequest request = new QueryTransferBatchesRequest();
        request.setOutBatchNo(outTradeNo);
        request.setNeedQueryDetail(true);
        request.setDetailStatus("ALL");
        request.setOffset(0);
        request.setLimit(100);

        log.info("发起查询商家转账给用户-{}", cn.hutool.json.JSONUtil.toJsonStr(request));

        QueryTransferBatchesResult batchesResult = wxPayService.getTransferService().transferBatchesOutBatchNo(request);

        log.info("查询商家转账给用户结果-{}", cn.hutool.json.JSONUtil.toJsonStr(request));

        if(null == batchesResult ||
                null == batchesResult.getTransferBatch() ||
                "WAIT_PAY".equals(batchesResult.getTransferBatch().getBatchStatus())){
            throw new WxPayException("【微信商家转账】查询结果不存在");
        }

        if(batchesResult.getTransferDetailList().size() < 1){
            throw new WxPayException("【微信商家转账】查询结果不存在");
        }

        QueryTransferBatchesResult.TransferDetail transferDetail = batchesResult.getTransferDetailList().get(0);
        if(!outTradeNo.equals(transferDetail.getOutDetailNo())){
            throw new WxPayException("【微信商家转账】查询交易号不匹配");
        }

        return transferDetail;
    }
}
